/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.six.expclientes;

import com.sig.utilerias.FuncionesValidacion;
import com.sig.utilerias.entity.EntityManagerFactory;
import com.six.dto.GcliCliente;
import com.six.expclientes.util.ClienteChildFactory;
import com.six.expclientes.util.ClienteRootNode;
import java.util.List;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.swing.SwingUtilities;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.explorer.ExplorerManager;
import org.openide.explorer.ExplorerUtils;
import org.openide.nodes.Children;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.openide.util.RequestProcessor;
import org.openide.windows.WindowManager;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(
        dtd = "-//com.six.expclientes//ExploradorClientes//EN",
        autostore = false)
@TopComponent.Description(
        preferredID = "ExploradorClientesTopComponent",
        //iconBase="SET/PATH/TO/ICON/HERE", 
        persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "explorer", openAtStartup = true)
@ActionID(category = "Window", id = "com.six.expclientes.ExploradorClientesTopComponent")
@ActionReference(path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(
        displayName = "#CTL_ExploradorClientesAction",
        preferredID = "ExploradorClientesTopComponent")
@Messages({
    "CTL_ExploradorClientesAction=Explorador Clientes",
    "CTL_ExploradorClientesTopComponent=Explorador Clientes",
    "HINT_ExploradorClientesTopComponent=Explorador Clientes"
})
public final class ExploradorClientesTopComponent extends TopComponent implements ExplorerManager.Provider {

    private static final ExplorerManager em = new ExplorerManager();
    private static final String PREFERRED_ID = "ExploradorClientesTopComponent";
    private static ExploradorClientesTopComponent instance;

    public ExploradorClientesTopComponent() {
        initComponents();
        setName(Bundle.CTL_ExploradorClientesTopComponent());
        setToolTipText(Bundle.HINT_ExploradorClientesTopComponent());
        putClientProperty(TopComponent.PROP_CLOSING_DISABLED, Boolean.TRUE);
        putClientProperty(TopComponent.PROP_DRAGGING_DISABLED, Boolean.TRUE);
        putClientProperty(TopComponent.PROP_MAXIMIZATION_DISABLED, Boolean.TRUE);
        putClientProperty(TopComponent.PROP_SLIDING_DISABLED, Boolean.TRUE);
        putClientProperty(TopComponent.PROP_UNDOCKING_DISABLED, Boolean.TRUE);
        putClientProperty(TopComponent.PROP_KEEP_PREFERRED_SIZE_WHEN_SLIDED_IN, Boolean.TRUE);

        RequestProcessor.getDefault().post(new Runnable() {
            @Override
            public void run() {
                refreshNode();
            }
        });
        associateLookup(ExplorerUtils.createLookup(em, getActionMap()));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jtfNombre = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jtfApPaterno = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jtfApMaterno = new javax.swing.JTextField();
        jbBuscar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        beanTreeView1 = new org.openide.explorer.view.BeanTreeView();

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(ExploradorClientesTopComponent.class, "ExploradorClientesTopComponent.jLabel1.text")); // NOI18N

        jtfNombre.setDocument(new com.sig.utilerias.text.JTextFieldLimit(100));
        jtfNombre.setText(org.openide.util.NbBundle.getMessage(ExploradorClientesTopComponent.class, "ExploradorClientesTopComponent.jtfNombre.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(ExploradorClientesTopComponent.class, "ExploradorClientesTopComponent.jLabel2.text")); // NOI18N

        jtfApPaterno.setDocument(new com.sig.utilerias.text.JTextFieldLimit(100));
        jtfApPaterno.setText(org.openide.util.NbBundle.getMessage(ExploradorClientesTopComponent.class, "ExploradorClientesTopComponent.jtfApPaterno.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(ExploradorClientesTopComponent.class, "ExploradorClientesTopComponent.jLabel3.text")); // NOI18N

        jtfApMaterno.setDocument(new com.sig.utilerias.text.JTextFieldLimit(100));
        jtfApMaterno.setText(org.openide.util.NbBundle.getMessage(ExploradorClientesTopComponent.class, "ExploradorClientesTopComponent.jtfApMaterno.text")); // NOI18N

        jbBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/six/expclientes/resources/usuario_buscar.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(jbBuscar, org.openide.util.NbBundle.getMessage(ExploradorClientesTopComponent.class, "ExploradorClientesTopComponent.jbBuscar.text")); // NOI18N
        jbBuscar.setToolTipText(org.openide.util.NbBundle.getMessage(ExploradorClientesTopComponent.class, "ExploradorClientesTopComponent.jbBuscar.text")); // NOI18N
        jbBuscar.setPreferredSize(new java.awt.Dimension(30, 30));
        jbBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbBuscarActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(beanTreeView1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(beanTreeView1, javax.swing.GroupLayout.DEFAULT_SIZE, 449, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jbBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jtfApPaterno)
                            .addComponent(jtfApMaterno)
                            .addComponent(jtfNombre))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jtfNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jtfApPaterno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jtfApMaterno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(2, 2, 2)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jbBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbBuscarActionPerformed
        // TODO add your handling code here:
        refreshNode();
    }//GEN-LAST:event_jbBuscarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private org.openide.explorer.view.BeanTreeView beanTreeView1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton jbBuscar;
    private static javax.swing.JTextField jtfApMaterno;
    private static javax.swing.JTextField jtfApPaterno;
    private static javax.swing.JTextField jtfNombre;
    // End of variables declaration//GEN-END:variables

    @Override
    public void componentOpened() {
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    public static void refreshNode() {
        EntityManager entityManager = EntityManagerFactory.getEntityManager();
        StringBuilder query = new StringBuilder("SELECT g FROM GcliCliente g");
        boolean where = false;

        if (FuncionesValidacion.esValido(jtfNombre.getText())) {
            where = true;
            query.append(" where upper(g.idPersona.nombre) like upper(:nombre) ");
        }
        if (FuncionesValidacion.esValido(jtfApPaterno.getText())) {
            if (where) {
                query.append(" and upper(g.idPersona.apellidoPaterno) like upper(:apellidoPaterno) ");
            } else {
                where = true;
                query.append(" where upper(g.idPersona.apellidoPaterno) like upper(:apellidoPaterno) ");
            }
        }
        if (FuncionesValidacion.esValido(jtfApMaterno.getText())) {
            if (where) {
                query.append(" and upper(g.idPersona.apellidoMaterno) like upper(:apellidoMaterno) ");
            } else {
                query.append(" where upper(g.idPersona.apellidoMaterno) like upper(:apellidoMaterno) ");
            }
        }
        final TypedQuery<GcliCliente> typedQuery = entityManager.createQuery(query.toString(), GcliCliente.class);
        if (FuncionesValidacion.esValido(jtfNombre.getText())) {
            typedQuery.setParameter("nombre", "%" + jtfNombre.getText() + "%");
        }
        if (FuncionesValidacion.esValido(jtfApPaterno.getText())) {
            typedQuery.setParameter("apellidoPaterno", "%" + jtfApPaterno.getText() + "%");
        }
        if (FuncionesValidacion.esValido(jtfApMaterno.getText())) {
            typedQuery.setParameter("apellidoMaterno", "%" + jtfApMaterno.getText() + "%");
        }
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                ProgressHandle handle = ProgressHandleFactory.createHandle("Buscando");
                handle.start();
                List<GcliCliente> resultList = typedQuery.getResultList();
                em.setRootContext(new ClienteRootNode(Children.create(new ClienteChildFactory(resultList), true)));
                handle.finish();
            }
        });
    }

    @Override
    public ExplorerManager getExplorerManager() {
        return em;
    }

    public static synchronized ExploradorClientesTopComponent getDefault() {
        if (instance == null) {
            instance = new ExploradorClientesTopComponent();
        }
        return instance;
    }

    public static synchronized ExploradorClientesTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(ExploradorClientesTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof ExploradorClientesTopComponent) {
            return (ExploradorClientesTopComponent) win;
        }
        Logger.getLogger(ExploradorClientesTopComponent.class.getName()).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID
                + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }
}
